home *** CD-ROM | disk | FTP | other *** search
- Path: news.sprintlink.net!datalytics!usenet
- From: Rob Stewart <stew@datalytics.com>
- Newsgroups: comp.lang.c++
- Subject: Re: Calling the wrong constructor
- Date: Fri, 19 Apr 1996 17:12:09 -0400
- Organization: Datalytics, Inc
- Message-ID: <317801A9.4B35@datalytics.com>
- References: <4kot87$796@earth.njcc.com> <Andrew_Carol-1804962001240001@17.127.18.252>
- NNTP-Posting-Host: 204.62.224.71
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (WinNT; I)
-
- Andrew wrote:
- >
- > In article <4kot87$796@earth.njcc.com>, mike@pluto.njcc.com (Michael
- > Hohenshilt) wrote:
- >
- > > This might seem like a basic question, but lets say you something set u
- > > like the following:
- > >
- > > class Parent { Parent() { allocsomething} ~Parent() { deletesomething }... };
- > > class Foo : Parent { Foo() { allocsomething } ~Foo() {deletesomething }... };
- > > class Contain { Parent *ptr; ... };
- > >
- > > both parent, and foo allocate memory, and will free it up when being
- > > destructed. Contain just holds a pointer of type Parent, and its
- > > constructor takes such a pointer as a parameter.
- > > If I store a pointer of type Foo into contain.ptr and discard that
- > > pointer. Is there any way to have contain (via destructors) free up all
- > > memory allocated by Foo and/or Parent?
- >
- > Assuming that "Contain" keeps a copy of the 'ptr'...
- >
- > ~Contain() { delete ptr; }
- >
- > This will call the destructor of Foo and Parent...
- >
-
- Assuming Contain::ptr actually points to a Foo rather than a
- Parent, you need virtual destructors in Parent and Foo. When
- you do this, the destructor of Foo will be invoked through the
- virtual function mechanism (vtable). It, in turn, will call
- Parent's destructor.
-
- --
- Robert Stewart | My opinions are usually my own.
- Datalytics, Inc. | stew@datalytics.com
-